class Activityimporter
  # 科技活动有点特殊需要分开处理

	def self.import
		(2005...2016).each do |year|
		  puts "开始导入#{year}年科技活动"

      #对于科技活动　05至07需要导入54 55 56；10年缺B57，需要导入55 56；08至15需导入55 56 57
    
		  case year
		  when 2005...2008
		  	docs = {"B54" => ActivityProfile, "B55" => ActivityProfile, "B56" => ActivityProfile}
		  	numbers = ["B54","B55","B56"]
		  when 2010
		  	docs = {"B55" => ActivityProfile, "B56" => ActivityProfile}
		  	numbers = ["B55","B56"]
		  else
		  	docs = {"B55" => ActivityProfile, "B56" => ActivityProfile, "B57" => ActivityProfile}
		  	numbers = ["B55","B56","B57"]
		  end

			Dir.glob("#{Rails.root}/docs/#{year}/*.xls").select {|xls| numbers.include?(xls[/B(\d)+/]) }.sort.each do |path|

				puts path
		  
		    ss = Roo::Excel.new(path)
				ss.sheets.each do |s|
				  ss.default_sheet = s
				  ((ss.first_row+1)..ss.last_row).each do |i|
		        #这里正则是用来匹配从左往右数第一个字段是否包括大学或者学院，这样处理的话即使文档行数不确定也不会出错
				  	if ss.cell(i,1) && ss.cell(i,1) =~ /(大学|学院)/
					  	hash = {}
					    begin
					    	school = School.find_or_create_by(name: ss.cell(i,1).to_s.strip)

					      model = docs[path[/B(\d)+/]]
					      model.table_head[year.to_s].each_with_index do |k,index|
					      	hash[k] = ss.cell(i,index+2).to_i
					      end
					      hash[:school_id] = school.id
					      hash[:record_year] = year
					      model.create(hash)
					      # SchoolTag.create(school_id: school.id,)
					    rescue Exception=>e
					      p e
					    end
					  else
					  	next
					  end
				  end
				end
		  end

		  puts "#{year}年科技活动导入完毕"
		end
	end
end